package com.weilai.controller;

import com.github.pagehelper.PageInfo;
import com.weilai.controller.exceptionHandler.BusinessException;
import com.weilai.controller.exceptionHandler.Code;
import com.weilai.controller.exceptionHandler.SystemException;
import com.weilai.domain.Posts;
import com.weilai.domain.Thought;
import com.weilai.domain.User;
import com.weilai.domain.Videos;
import com.weilai.service.FollowersService;
import com.weilai.service.PostsService;
import com.weilai.service.ThoughtService;
import com.weilai.service.UserService;
import com.weilai.util.UploadUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;

@Controller
@Api(tags = "想法",description = "对想法进行相关操作的接口")
public class ThoughtController {
    @Autowired
    private ThoughtService thoughtService;
    @Autowired
    private UserService userService;
    @Autowired
    private PostsService postsService;
    @Autowired
    private FollowersService followersService;

    // 推荐发布想法
    @ApiOperation(value = "添加想法的方法")
    @PostMapping("/thought/add")
    public String recommendAdd(@RequestParam String title,
                                     @RequestParam String content,
                                     @RequestParam int code,
                               RedirectAttributes redirectAttributes,
                               HttpServletRequest request) {
        try {
            // 参数校验
            if (title == null || title.trim().isEmpty()) {
                throw new BusinessException(Code.PROJECT_VALIDATE_ERROR, "标题不能为空");
            }
            if (content == null || content.trim().isEmpty()) {
                throw new BusinessException(Code.PROJECT_VALIDATE_ERROR, "内容不能为空");
            }

            Thought thought = new Thought();
            thought.setTitle(title);
            thought.setContent(content);
            int userId = (int) request.getSession().getAttribute("userId");
            thought.setUserId(userId);
            //获取当前时间
            LocalDateTime now = LocalDateTime.now();
            Date date = Date.from(now.atZone(ZoneId.systemDefault()).toInstant());
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            String formattedDate = now.format(formatter);
            thought.setCreateTime(formattedDate);
            thought.setUpdateTime(formattedDate);

            thoughtService.add(thought);
            redirectAttributes.addFlashAttribute("result", "添加成功");
            redirectAttributes.addFlashAttribute("time", formattedDate);


            //根据code判断跳转到哪个页面，1是推荐，2是关注，3是热搜,4是创作中心主页，5视频，6想法
            if(code==1){
                return "redirect:/mainPageRecommend";
            }
            else if(code==2){
                return "redirect:/mainPageAttention";
            }
            else if(code==3){
                return "redirect:/mainPageTrending";
            }
            else if(code==4){
                return "redirect:/creativeCenter";
            }
            else if(code==5){
                return "redirect:/mainPageVedio";
            }
            else if(code==6){
                return "redirect:/thoughtMainPage";
            }
            else{
                throw new BusinessException(Code.PROJECT_VALIDATE_ERROR, "无效的页面代码");
            }
        } catch (BusinessException e) {
            throw e; // 业务异常直接抛出
        } catch (Exception e) {
            throw new SystemException(Code.SYSTEM_DB_ERROR, "发布想法时数据库错误", e);
        }
    }
    // 删除想法
    @ApiOperation(value = "删除想法的方法")
    @PostMapping("/thought/delete")
    @ResponseBody
    public Map<String, Object> deleteById(@RequestParam int id) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 先检查是否存在
            Thought thought = thoughtService.selectById(id);
            if (thought == null) {
                throw new BusinessException(Code.PROJECT_DATA_NOT_FOUND, "该想法不存在或已被删除");
            }

            thoughtService.deleteById(id);
            result.put("message", "删除成功");
            result.put("page","/personCenterIdea");
        } catch (BusinessException e) {
            result.put("message", e.getMessage());
        } catch (Exception e) {
            result.put("message", "删除想法失败");
        }
        return result;
    }
    // 回显数据以便修改想法
    @ApiOperation(value = "回显数据的方法")
    @GetMapping("/updateThought")
    public ModelAndView updatePosts(@RequestParam int id) {
        try {
            Thought thought = thoughtService.selectById(id);
            if (thought == null) {
                throw new BusinessException(Code.PROJECT_DATA_NOT_FOUND, "未找到该想法");
            }

            ModelAndView mav = new ModelAndView();
            mav.addObject("thought", thought);
            mav.setViewName("updatePage");
            return mav;
        } catch (BusinessException e) {
            throw e;
        } catch (Exception e) {
            throw new SystemException(Code.SYSTEM_DB_ERROR, "查询想法时数据库错误", e);
        }
    }

    // 修改想法
    @ApiOperation(value = "修改想法的方法")
    @PostMapping("/thoughtUpdate")
    public ModelAndView update(@RequestParam int id,
                               @RequestParam String title,
                               @RequestParam String content) {
        try {
            // 参数校验
            if (title == null || title.trim().isEmpty()) {
                throw new BusinessException(Code.PROJECT_VALIDATE_ERROR, "标题不能为空");
            }
            if (content == null || content.trim().isEmpty()) {
                throw new BusinessException(Code.PROJECT_VALIDATE_ERROR, "内容不能为空");
            }

            Thought existingThought = thoughtService.selectById(id);
            if (existingThought == null) {
                throw new BusinessException(Code.PROJECT_DATA_NOT_FOUND, "未查询到该想法");
            }

            Thought thought = new Thought();
            thought.setId(id);
            thought.setTitle(title);
            thought.setContent(content);

            thoughtService.update(thought);
            ModelAndView mav = new ModelAndView();
            mav.addObject("result", "更新成功");
            mav.setViewName("userMainPage");
            return mav;
        } catch (BusinessException e) {
            throw e;
        } catch (Exception e) {
            throw new SystemException(Code.SYSTEM_DB_ERROR, "修改想法时数据库错误", e);
        }
    }
    //在首页查询所有想法
    @ApiOperation(value ="首页初始想法加载（前10条）")
    @GetMapping("/thoughtMainPage")
    public ModelAndView loadInitialThought(HttpServletRequest request,
                                          @RequestParam(defaultValue = "1") int pageNum,
                                          @RequestParam(defaultValue = "15") int pageSize) {
        try {
            //获取想法分页数据
            PageInfo<Thought> pageInfo = thoughtService.selectAll(pageNum, pageSize);
            if (pageInfo.getList().isEmpty() || pageInfo == null) {
                throw new BusinessException(Code.PROJECT_DATA_NOT_FOUND, "暂无数据");
            }
            //获取想法对应用户的信息
            List<User> users = new ArrayList<>();
            for (Thought thought : pageInfo.getList()) {
                User user = userService.getUserById(thought.getUserId());
                users.add(user);
            }
            // 判断用户角色，决定返回的视图
            User user = (User) request.getSession().getAttribute("user");
            String viewName = "thoughtMainPage";
            if (user != null && "admin".equals(user.getRole())) {
                viewName += "Manager";

            }
            return new ModelAndView(viewName)
                    .addObject("pageInfo", pageInfo)
                    .addObject("users", users);
        } catch (BusinessException e) {
            throw new BusinessException(Code.PROJECT_DATA_NOT_FOUND,"业务异常");
        } catch (Exception e) {
            throw new SystemException(Code.SYSTEM_DB_ERROR, "查询列表失败",e);
        }
    }
    @ApiOperation(value = "分页加载更多想法")
    @GetMapping("/thoughtMainPage/more")
    public ResponseEntity<Map<String, Object>> loadMoreThought(
            HttpServletRequest request,
            @RequestParam(defaultValue = "2") int pageNum,
            @RequestParam(defaultValue = "15") int pageSize
    ) {

        try {
            //获取想法分页数据
            PageInfo<Thought> pageInfo = thoughtService.selectAll(pageNum, pageSize);
            if (pageInfo.getList().isEmpty() || pageInfo == null) {
                throw new BusinessException(Code.PROJECT_DATA_NOT_FOUND, "暂无数据");
            }

            // 获取想法对应的用户信息，添加空值检查
            List<User> users = new ArrayList<>();
            for (Thought thought : pageInfo.getList()) {
                User user = userService.getUserById(thought.getUserId());
                if (user != null) {
                    users.add(user);
                } else {
                    return ResponseEntity.ok(Collections.singletonMap("message", "未查询到用户"));
                }
            }

            // 判断用户角色
            User user = (User) request.getSession().getAttribute("user");

            // 构建返回数据
            Map<String, Object> response = new HashMap<>();
            response.put("pageInfo", pageInfo);
            response.put("users", users);

            return ResponseEntity.ok(response);
        } catch (BusinessException e) {
            // 记录日志
            e.printStackTrace();
            // 根据业务异常返回合适的HTTP状态码，比如400表示请求有误
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(Collections.singletonMap("error", e.getMessage()));
        } catch (Exception e) {
            // 记录日志
            e.printStackTrace();
            // 对于其他异常返回500表示服务器内部错误
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(Collections.singletonMap("error", "查询列表失败"));
        }
    }
    //根据id查询想法
    @ApiOperation(value="根据id查询想法的方法")
    @GetMapping("/thought/select/id")
    public ModelAndView selectById(@RequestParam int id, HttpServletRequest request) {
        ModelAndView mav = new ModelAndView();

        // 参数校验
        if (id <= 0) {
            throw new BusinessException(
                    Code.PROJECT_VALIDATE_ERROR,
                    "想法ID必须为正整数"
            );
        }

        try {
            // 查询想法
            Thought thought = thoughtService.selectById(id);
            if (thought == null) {
                throw new BusinessException(
                        Code.PROJECT_DATA_NOT_FOUND,
                        "想法不存在"
                );
            }

            // 查询用户信息
            User user = userService.getUserById(thought.getUserId());

            if (user == null) {
                throw new BusinessException(
                        Code.PROJECT_DATA_NOT_FOUND,
                        "用户不存在"
                );
            }
            user.setEmail("***");
            user.setPassword("***");
            // 查询用户相关数据
            List<Posts> p = postsService.selectByUserId(thought.getUserId());
            List<Thought> t = thoughtService.selectAllUsersThought(thought.getUserId());
            List<User> f = followersService.selectFansById(thought.getUserId());

            User user1 =(User) request.getSession().getAttribute("user");
            boolean isFollowing = false;
            if(user1 != null) {
                //判断是否关注
                isFollowing = followersService.isFollowing(user1.getId(), thought.getUserId());
            }

            // 设置视图数据

            mav.addObject("user", user);
            mav.addObject("thought", thought);
            mav.addObject("postsNum", p != null ? p.size() : 0);
            mav.addObject("thoughtNum", t != null ? t.size() : 0);
            mav.addObject("fansNum", f != null ? f.size() : 0);
            mav.addObject("isFollowing",isFollowing);//添加关注状态到视图
            mav.setViewName("thoughtMainPageDetail");

        } catch (BusinessException e) {
            // 业务异常直接抛出
            throw e;
        } catch (Exception e) {
            // 系统异常包装后抛出
            throw new SystemException(
                    Code.SYSTEM_DB_ERROR,
                    "查询帖子详情失败",
                    e
            );
        }

        return mav;
    }


    // 查询别人所有想法
    @ApiOperation(value = "查询别人所有想法的方法")
    @GetMapping("/thought/selectAllUsersThought")
    public ModelAndView selectAllUsersThought(@RequestParam int userId) {
        try {
            List<Thought> thoughts = thoughtService.selectAllUsersThought(userId);
            if (thoughts == null || thoughts.isEmpty()) {
                throw new BusinessException(Code.PROJECT_DATA_NOT_FOUND, "该用户暂无想法");
            }

            List<User> users = new ArrayList<>();
            for (Thought t : thoughts) {
                User user = userService.getUserById(t.getUserId());
                if (user == null) {
                    throw new BusinessException(Code.PROJECT_DATA_NOT_FOUND, "用户信息不存在");
                }
                users.add(user);
            }

            ModelAndView mav = new ModelAndView();
            mav.addObject("user", users);
            mav.addObject("thought", thoughts);
            mav.setViewName("allUsersThought");
            return mav;
        } catch (BusinessException e) {
            throw e;
        } catch (Exception e) {
            throw new SystemException(Code.SYSTEM_DB_ERROR, "查询用户想法时数据库错误", e);
        }
    }

    // 查询自己所有想法
    @ApiOperation(value = "查询自己所有想法的方法")
    @GetMapping("/thought/selectMyAllThought")
    public ModelAndView selectMyAllThought(HttpServletRequest request) {
        try {
            int userId = (int) request.getSession().getAttribute("userId");
            List<Thought> thoughts = thoughtService.selectMyAllThought(userId);

            ModelAndView mav = new ModelAndView();
            if (thoughts == null || thoughts.isEmpty()) {
                mav.addObject("message", "您还没有发布过想法");
            } else {
                List<User> users = new ArrayList<>();
                for (Thought t : thoughts) {
                    User user = userService.getUserById(t.getUserId());
                    users.add(user);
                }
                mav.addObject("user", users);
                mav.addObject("thought", thoughts);
            }
            mav.setViewName("personCenterIdea");
            return mav;
        } catch (Exception e) {
            throw new SystemException(Code.SYSTEM_DB_ERROR, "查询个人想法时数据库错误", e);
        }
    }

//    // 根据id查询想法
//    @ApiOperation(value = "根据id查询想法的方法")
//    @GetMapping("/thought/select/id")
//    public ModelAndView selectById(@RequestParam int id) {
//        try {
//            Thought thought = thoughtService.selectById(id);
//            if (thought == null) {
//                throw new BusinessException(Code.PROJECT_DATA_NOT_FOUND, "未找到该想法");
//            }
//
//            User user = userService.getUserById(thought.getUserId());
//            if (user == null) {
//                throw new BusinessException(Code.PROJECT_DATA_NOT_FOUND, "用户信息不存在");
//            }
//
//            ModelAndView mav = new ModelAndView();
//            mav.addObject("user", user);
//            mav.addObject("thought", thought);
//            mav.setViewName("idPosts");
//            return mav;
//        } catch (BusinessException e) {
//            throw e;
//        } catch (Exception e) {
//            throw new SystemException(Code.SYSTEM_DB_ERROR, "查询想法详情时数据库错误", e);
//        }
//    }




}
